package net.kaaass.tools.gradequery.captcha;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 简单的滤波
 */
public class Filtering {
    public static BufferedImage binaryzation(BufferedImage image)
            throws Exception {
        int width = image.getWidth();
        int height = image.getHeight();
        for (int x = 0; x < width; ++x) {
            for (int y = 0; y < height; ++y) {
                if (isBackgroundColor(image.getRGB(x, y))) {
                    image.setRGB(x, y, Color.WHITE.getRGB());
                } else if(isBackgroundColor2(image.getRGB(x, y))) {
                    image.setRGB(x, y, Color.WHITE.getRGB());
                } else {
                    image.setRGB(x, y, Color.BLACK.getRGB());
                }
            }
        }
        return image;
    }

    private static boolean isBackgroundColor(int colorInt) {
        Color color = new Color(colorInt);
        int inter;
        inter = Math.abs(color.getRed() - color.getGreen()) + Math.abs(color.getGreen() - color.getBlue()) + Math.abs(color.getRed() - color.getBlue());
        return inter < 40 && color.getRed() > 128;
    }

    private static boolean isBackgroundColor2(int colorInt) {
        Color color = new Color(colorInt);
        return color.getRed()+color.getGreen()+color.getBlue() > 550;
    }
}
